<template>
  <div class="fee-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>费用管理</h1>
      <el-button type="primary" @click="showAddFeeDialog">
        <el-icon><Plus /></el-icon>
        新增费用记录
      </el-button>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ totalAmount }}</div>
            <div class="stat-label">总费用(元)</div>
            <div class="stat-icon total"><el-icon><WalletFilled /></el-icon></div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ pendingAmount }}</div>
            <div class="stat-label">待收费用(元)</div>
            <div class="stat-icon pending"><el-icon><WarningFilled /></el-icon></div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ paidAmount }}</div>
            <div class="stat-label">已收费用(元)</div>
            <div class="stat-icon paid"><el-icon><Check /></el-icon></div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ overdueAmount }}</div>
            <div class="stat-label">逾期费用(元)</div>
            <div class="stat-icon overdue"><el-icon><CircleClose /></el-icon></div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-card>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input v-model="searchQuery" placeholder="搜索费用编号/房产地址/住户姓名" />
          </el-col>
          <el-col :span="6">
            <el-select v-model="feeTypeFilter" placeholder="选择费用类型">
              <el-option label="全部类型" value="" />
              <el-option label="物业费" value="property_fee" />
              <el-option label="水电费" value="utilities" />
              <el-option label="停车费" value="parking_fee" />
              <el-option label="维修费" value="repair_fee" />
              <el-option label="其他费用" value="other" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="paymentStatusFilter" placeholder="选择支付状态">
              <el-option label="全部状态" value="" />
              <el-option label="待支付" value="pending" />
              <el-option label="已支付" value="paid" />
              <el-option label="已逾期" value="overdue" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 费用列表 -->
    <div class="fee-list-section">
      <el-card>
        <el-table :data="paginatedFees" style="width: 100%" height="500px">
          <el-table-column prop="id" label="费用编号" width="140" />
          <el-table-column prop="propertyInfo" label="房产信息" width="160" />
          <el-table-column prop="residentName" label="住户姓名" width="120" />
          <el-table-column prop="feeType" label="费用类型" width="120">
            <template #default="scope">
              {{ getFeeTypeText(scope.row.feeType) }}
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额(元)" width="120">
            <template #default="scope">
              <span class="amount-text">{{ scope.row.amount.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="dueDate" label="缴费截止日" width="160" />
          <el-table-column prop="paymentStatus" label="支付状态" width="120">
            <template #default="scope">
              <el-tag :type="getPaymentStatusType(scope.row.paymentStatus)">
                {{ getPaymentStatusText(scope.row.paymentStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="paymentTime" label="支付时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="showFeeDetail(scope.row)">查看详情</el-button>
              <el-button v-if="scope.row.paymentStatus !== 'paid'" type="success" link @click="confirmPayment(scope.row.id)">标记支付</el-button>
              <el-button type="danger" link @click="confirmDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredFees.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑费用对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="房产信息">
          <el-input v-model="formData.propertyInfo" placeholder="请输入房产信息" />
        </el-form-item>
        <el-form-item label="住户姓名">
          <el-input v-model="formData.residentName" placeholder="请输入住户姓名" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="formData.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="费用类型">
          <el-select v-model="formData.feeType" placeholder="请选择费用类型">
            <el-option label="物业费" value="property_fee" />
            <el-option label="水电费" value="utilities" />
            <el-option label="停车费" value="parking_fee" />
            <el-option label="维修费" value="repair_fee" />
            <el-option label="其他费用" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额(元)">
          <el-input v-model.number="formData.amount" type="number" placeholder="请输入金额" min="0" step="0.01" />
        </el-form-item>
        <el-form-item label="费用周期">
          <el-input v-model="formData.feePeriod" placeholder="例如：2024年1月" />
        </el-form-item>
        <el-form-item label="缴费截止日">
          <el-date-picker
            v-model="formData.dueDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注信息" v-if="!isEditMode">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 费用详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="费用详情"
      width="700px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="费用编号">{{ selectedFee.id }}</el-descriptions-item>
        <el-descriptions-item label="房产信息">{{ selectedFee.propertyInfo }}</el-descriptions-item>
        <el-descriptions-item label="住户姓名">{{ selectedFee.residentName }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ selectedFee.contact }}</el-descriptions-item>
        <el-descriptions-item label="费用类型">{{ getFeeTypeText(selectedFee.feeType) }}</el-descriptions-item>
        <el-descriptions-item label="费用周期">{{ selectedFee.feePeriod }}</el-descriptions-item>
        <el-descriptions-item label="金额(元)">{{ selectedFee.amount.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="缴费截止日">{{ selectedFee.dueDate }}</el-descriptions-item>
        <el-descriptions-item label="支付状态">{{ getPaymentStatusText(selectedFee.paymentStatus) }}</el-descriptions-item>
        <el-descriptions-item label="支付时间" v-if="selectedFee.paymentTime">{{ selectedFee.paymentTime }}</el-descriptions-item>
        <el-descriptions-item label="支付方式" v-if="selectedFee.paymentMethod">{{ selectedFee.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="备注信息" v-if="selectedFee.remark">{{ selectedFee.remark }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ selectedFee.createTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { 
  Plus, WalletFilled, WarningFilled, Check, CircleClose 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 状态管理
const fees = ref([])
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref({})
const selectedFee = ref({})
const isEditMode = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')
const feeTypeFilter = ref('')
const paymentStatusFilter = ref('')

// 统计数据计算
const totalAmount = computed(() => {
  return fees.value.reduce((sum, fee) => sum + fee.amount, 0).toFixed(2)
})

const pendingAmount = computed(() => {
  return fees.value.filter(fee => fee.paymentStatus === 'pending')
    .reduce((sum, fee) => sum + fee.amount, 0).toFixed(2)
})

const paidAmount = computed(() => {
  return fees.value.filter(fee => fee.paymentStatus === 'paid')
    .reduce((sum, fee) => sum + fee.amount, 0).toFixed(2)
})

const overdueAmount = computed(() => {
  return fees.value.filter(fee => fee.paymentStatus === 'overdue')
    .reduce((sum, fee) => sum + fee.amount, 0).toFixed(2)
})

// 筛选后的费用列表
const filteredFees = computed(() => {
  let filtered = fees.value
  
  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(fee => 
      fee.id.toLowerCase().includes(query) ||
      fee.propertyInfo.toLowerCase().includes(query) ||
      fee.residentName.toLowerCase().includes(query)
    )
  }
  
  // 类型筛选
  if (feeTypeFilter.value) {
    filtered = filtered.filter(fee => fee.feeType === feeTypeFilter.value)
  }
  
  // 状态筛选
  if (paymentStatusFilter.value) {
    filtered = filtered.filter(fee => fee.paymentStatus === paymentStatusFilter.value)
  }
  
  // 按截止日期倒序排序
  filtered.sort((a, b) => new Date(b.dueDate) - new Date(a.dueDate))
  
  return filtered
})

// 分页后的费用列表
const paginatedFees = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredFees.value.slice(start, end)
})

// 初始化数据
onMounted(() => {
  initMockData()
})

// 初始化模拟数据
function initMockData() {
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)
  const nextWeek = new Date(today)
  nextWeek.setDate(nextWeek.getDate() + 7)
  const lastMonth = new Date(today)
  lastMonth.setMonth(lastMonth.getMonth() - 1)

  fees.value = [
    {
      id: 'FEE2024001',
      propertyInfo: '1号楼 302室',
      residentName: '张三',
      contact: '13812345678',
      feeType: 'property_fee',
      feePeriod: '2024年1月',
      amount: 150.00,
      dueDate: nextWeek.toISOString().split('T')[0],
      paymentStatus: 'pending',
      createTime: '2024-01-01 09:00:00',
      remark: '当月物业费'
    },
    {
      id: 'FEE2024002',
      propertyInfo: '2号楼 501室',
      residentName: '李四',
      contact: '13987654321',
      feeType: 'utilities',
      feePeriod: '2024年1月',
      amount: 89.50,
      dueDate: nextWeek.toISOString().split('T')[0],
      paymentStatus: 'paid',
      paymentTime: yesterday.toISOString().split('T')[0] + ' 14:30:00',
      paymentMethod: '支付宝',
      createTime: '2024-01-01 09:00:00'
    },
    {
      id: 'FEE2024003',
      propertyInfo: '3号楼 203室',
      residentName: '王五',
      contact: '13756789012',
      feeType: 'parking_fee',
      feePeriod: '2024年1月',
      amount: 300.00,
      dueDate: lastMonth.toISOString().split('T')[0],
      paymentStatus: 'overdue',
      createTime: '2024-01-01 09:00:00',
      remark: '月度停车费'
    },
    {
      id: 'FEE2024004',
      propertyInfo: '1号楼 804室',
      residentName: '赵六',
      contact: '13698765432',
      feeType: 'repair_fee',
      feePeriod: '2024年1月15日',
      amount: 200.00,
      dueDate: tomorrow.toISOString().split('T')[0],
      paymentStatus: 'pending',
      createTime: '2024-01-15 16:45:00',
      remark: '卫生间漏水维修费用'
    },
    {
      id: 'FEE2024005',
      propertyInfo: '2号楼 1102室',
      residentName: '钱七',
      contact: '13589012345',
      feeType: 'utilities',
      feePeriod: '2024年1月',
      amount: 120.30,
      dueDate: nextWeek.toISOString().split('T')[0],
      paymentStatus: 'pending',
      createTime: '2024-01-01 09:00:00'
    },
    {
      id: 'FEE2024006',
      propertyInfo: '3号楼 405室',
      residentName: '孙八',
      contact: '13478901234',
      feeType: 'property_fee',
      feePeriod: '2024年1月',
      amount: 180.00,
      dueDate: lastMonth.toISOString().split('T')[0],
      paymentStatus: 'paid',
      paymentTime: today.toISOString().split('T')[0] + ' 10:15:00',
      paymentMethod: '微信支付',
      createTime: '2024-01-01 09:00:00'
    },
    {
      id: 'FEE2024007',
      propertyInfo: '1号楼 602室',
      residentName: '周九',
      contact: '13367890123',
      feeType: 'other',
      feePeriod: '2024年1月',
      amount: 50.00,
      dueDate: nextWeek.toISOString().split('T')[0],
      paymentStatus: 'pending',
      createTime: '2024-01-20 14:20:00',
      remark: '公共区域清洁费'
    }
  ]
}

// 获取费用类型文本
function getFeeTypeText(type) {
  const typeMap = {
    property_fee: '物业费',
    utilities: '水电费',
    parking_fee: '停车费',
    repair_fee: '维修费',
    other: '其他费用'
  }
  return typeMap[type] || type
}

// 获取支付状态文本
function getPaymentStatusText(status) {
  const statusMap = {
    pending: '待支付',
    paid: '已支付',
    overdue: '已逾期'
  }
  return statusMap[status] || status
}

// 获取支付状态标签类型
function getPaymentStatusType(status) {
  const typeMap = {
    pending: 'warning',
    paid: 'success',
    overdue: 'danger'
  }
  return typeMap[status] || 'info'
}

// 显示新增费用对话框
function showAddFeeDialog() {
  isEditMode.value = false
  dialogTitle.value = '新增费用记录'
  const today = new Date()
  const nextMonth = new Date(today)
  nextMonth.setMonth(nextMonth.getMonth() + 1)
  
  formData.value = {
    propertyInfo: '',
    residentName: '',
    contact: '',
    feeType: '',
    feePeriod: `${today.getFullYear()}年${today.getMonth() + 1}月`,
    amount: 0,
    dueDate: nextMonth.toISOString().split('T')[0],
    remark: ''
  }
  dialogVisible.value = true
}

// 提交表单
function submitForm() {
  if (isEditMode.value) {
    // 更新费用信息
    const index = fees.value.findIndex(item => item.id === formData.value.id)
    if (index !== -1) {
      fees.value[index] = { ...fees.value[index], ...formData.value }
      ElMessage.success('费用信息更新成功')
    }
  } else {
    // 新增费用记录
    const newFee = {
      ...formData.value,
      id: `FEE${new Date().getFullYear()}${String(fees.value.length + 1).padStart(3, '0')}`,
      paymentStatus: 'pending',
      createTime: new Date().toLocaleString('zh-CN')
    }
    fees.value.unshift(newFee)
    ElMessage.success('费用记录添加成功')
  }
  dialogVisible.value = false
}

// 显示费用详情
function showFeeDetail(fee) {
  selectedFee.value = { ...fee }
  detailDialogVisible.value = true
}

// 确认支付
function confirmPayment(id) {
  ElMessageBox.confirm('确定要标记此费用为已支付吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const fee = fees.value.find(item => item.id === id)
    if (fee) {
      fee.paymentStatus = 'paid'
      fee.paymentTime = new Date().toLocaleString('zh-CN')
      fee.paymentMethod = '线下支付'
      ElMessage.success('费用已标记为已支付')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 确认删除
function confirmDelete(id) {
  ElMessageBox.confirm('确定要删除这条费用记录吗？此操作不可撤销。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger'
  }).then(() => {
    const index = fees.value.findIndex(item => item.id === id)
    if (index !== -1) {
      fees.value.splice(index, 1)
      ElMessage.success('费用记录已删除')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 搜索处理
function handleSearch() {
  currentPage.value = 1
}

// 重置筛选条件
function resetFilters() {
  searchQuery.value = ''
  feeTypeFilter.value = ''
  paymentStatusFilter.value = ''
  currentPage.value = 1
}

// 处理页码变化
function handleSizeChange(size) {
  pageSize.value = size
}

// 处理页面变化
function handleCurrentChange(current) {
  currentPage.value = current
}
</script>

<script>
export default {
  name: 'FeeManagementView'
}
</script>

<style scoped>
.fee-management-container {
  width: 100%;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 36px;
  opacity: 0.2;
}

.stat-icon.total {
  color: #909399;
}

.stat-icon.pending {
  color: #e6a23c;
}

.stat-icon.paid {
  color: #67c23a;
}

.stat-icon.overdue {
  color: #f56c6c;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 20px;
}

/* 费用列表样式 */
.fee-list-section {
  margin-bottom: 20px;
}

.amount-text {
  font-weight: bold;
  color: #606266;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>